﻿@using DCMS.Web.Extensions;
@using DCMS.Web.Framework;
@using DCMS.Web.Framework.UI;
@using DCMS.ViewModel.Models.WareHouses;
@model AllocationBillModel


<script type="text/javascript">

	jQuery(document).ready(function () {

		"use strict";

		// Init Theme Core
		Core.init();

		// Init Demo JS
		Demo.init();

        var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
		if (model.ReversedStatus) {
            $("#inkpadBox").hide();
            $("#inkpadBox1").css('display', 'block');
        }
		//快速调拨
		$('#QuickAllocation').multiselect({
			//buttonClass: 'multiselect dropdown-toggle btn btn-default btn-primary btn-block', display: true, onChange: function (e, t) {
			//	//var select = $(e).val();
			//	$(this).showModalAndSubmit($("#QuickAllocationWindow"), "/Common/AsynQuickAllocationPopup", null, "选择调拨方式", $("#QuickAllocationForm"), function () {
			//		//
			//	});
			//}
			buttonClass: 'multiselect dropdown-toggle btn btn-default btn-primary btn-block', display: true, onChange: function (e, t) {
				var allocationType = $("#QuickAllocation").val();

				if (allocationType == 0) {
					return false;
				}

				var allocationName = $("#QuickAllocation option:selected").text();

				//仓库
                var wareHouseId = $("#ShipmentWareHouseId").val();
				if (wareHouseId == 'undefined' || wareHouseId == undefined) {
					wareHouseId = 0;
				}

				$(this).showModalAndSubmit($("#QuickAllocationWindow"), "/Common/AsynQuickAllocationPopup?allocationType=" + allocationType + "&wareHouseId=" + wareHouseId, null, allocationName, $("#QuickAllocationForm"), function () {

					//送货员
					var deliveryUserId = $("#DeliveryUserId").val();
					if (deliveryUserId == 'undefined' || deliveryUserId == undefined) {
						deliveryUserId = 0;
					}
					//商品类别（不选默认所有类别）
					var categoryIds = "";
					$("input[name='CategoryName']:checked").each(function (a, b) {
						categoryIds = categoryIds + (categoryIds == "" ? "" : ",") + $(this).val();
					});
					//加载数据
					var loadDataNameIds = "";
					$("input[type='checkbox'][name='LoadDataName']:checked").each(function (a, b) {
						loadDataNameIds = loadDataNameIds + (loadDataNameIds == "" ? "" : ",") + $(this).val();
					});

					//验证
					//按拒收商品调拨
					if (allocationType == 1) {
						if ($("#ShipmentWareHouseId").val() == 0 || $("#ShipmentWareHouseId").val() == null || $("#ShipmentWareHouseId").val() == '') {
							$(this).showToastr("请选择出货仓库！");
							return false;
						}
						wareHouseId = $("#ShipmentWareHouseId").val();

						if (loadDataNameIds == "" || loadDataNameIds == 'undefined') {
							$(this).showToastr("请选择加载数据范围！");
							return false;
						}
					}
					//按销补货
					if (allocationType == 2) {

						if ($("#ShipmentWareHouseId").val() == 0 || $("#ShipmentWareHouseId").val() == null || $("#IncomeWareHouseId").val() == '') {
							$(this).showToastr("请选择出货仓库！");
							return false;
						}
						wareHouseId = $("#ShipmentWareHouseId").val();

						if (loadDataNameIds == "" || loadDataNameIds == 'undefined') {
							$(this).showToastr("请选择加载数据范围！");
							return false;
						}
					}
					//按退调拨
					if (allocationType == 3) {
						if ($("#ShipmentWareHouseId").val() == 0 || $("#ShipmentWareHouseId").val() == null || $("#ShipmentWareHouseId").val() == '') {
							$(this).showToastr("请选择出货仓库！");
							return false;
						}
						wareHouseId = $("#ShipmentWareHouseId").val();

						if (loadDataNameIds == "" || loadDataNameIds == 'undefined') {
							$(this).showToastr("请选择加载数据范围！");
							return false;
						}
					}

					var param = {
						allocationType: allocationType,
						wareHouseId: wareHouseId,
						deliveryUserId: deliveryUserId,
						categoryIds: categoryIds,
						loadDataNameIds: loadDataNameIds
					};
					debugger
					$.ajax({
						type: 'POST',
						url: "/Allocation/QuickAllocation",
						data: param,
						success: function (result) {
							if (result.Success) {
								$('#QuickAllocationWindow').modal('hide');
								//toastr.success(result.Message);

								//清空数据
								var trLength = $('#AllocationItems tr').length;
								$('#AllocationItems').bootstrapTable('refresh');
								for (var ii = 0; ii < trLength - 1; ii++) {
									$("#AllocationItems").bootstrapTable('updateRow', {
										index: ii, row: {
											ProductSKU: '',
											ProductId: 0,
											ProductName: '',
											BarCode: '',
											UnitConversion: '',
											Quantity: '',
											Units: '',
											UnitId: 0,
											UnitName: '',
											Amount: 0,
											Prices: '',
											TradePrice: 0,
											WholesaleAmount: 0,
											ProductTierPrices: '',  //价格体系
											OutgoingStock: '',
											WarehousingStock: '',
											StockQuantities: '', //库存数量
											BigQuantity: '',//大转小
											StrokeQuantity: '',//中转小
											SmallUnitId: '',  //小单位
											StrokeUnitId: '',  //中单位
											BigUnitId: ''  //大单位
										}
									});
								}

								if (result.rows != null && result.rows.length > 0) {

									result.rows.forEach(function (row, index) {

										var keys = Object.keys(row.Units);
										//默认价格
										var price = row.Prices[0].ProductPrice.TradePrice;
										////用户选择的价格体系
										//var defaultAmountId = 0;
										////初始最小单位单位
										//var unitId = row.SmallUnitId;
										////如果此商品有价格体系
										//row.ProductTierPrices.forEach(function (a, b) {
										//	var planIdTypeId = a.PricesPlanId + "_" + a.PriceTypeId;
										//	if (defaultAmountId == planIdTypeId) {
										//		price = a.SmallUnitPrice;
										//	}
										//});

										//出库库存
										var outgoingStock = 0;
										//入库库存
										var warehousingStock = 0;

										//出库仓库
										var shipmentWareHouseId = $("#ShipmentWareHouseId").val();
										//入库仓库
										var incomeWareHouseId = $("#IncomeWareHouseId").val();
										row.StockQuantities.forEach(function (a, b) {
											if (a.WareHouseId == shipmentWareHouseId) {
												outgoingStock = a.UsableQuantity;
											}
											if (a.WareHouseId == incomeWareHouseId) {
												warehousingStock = a.UsableQuantity;
											}
										});

										var rowNew =
										{
											ProductSKU: row.Sku,
											ProductId: row.Id,
											ProductName: row.Name,
											BarCode: row.SmallBarCode,
											UnitConversion: row.UnitConversion,
											Quantity: row.Quantity,
											Units: row.Units,
											UnitId: row.SmallUnitId,
											UnitName: keys[0],
											Amount: 0,
											Prices: row.Prices,
											TradePrice: price,
											WholesaleAmount: 0,
											ProductTierPrices: row.ProductTierPrices,  //价格体系
											OutgoingStock: outgoingStock,
											WarehousingStock: warehousingStock,
											StockQuantities: row.StockQuantities, //库存数量
											BigQuantity: row.BigQuantity,//大转小
											StrokeQuantity: row.StrokeQuantity,//中转小
											SmallUnitId: row.SmallUnitId,  //小单位
											StrokeUnitId: row.StrokeUnitId,  //中单位
											BigUnitId: row.BigUnitId  //大单位
										}
										//当前页面行数不够，添加行
										if (index >= trLength - 1) {
											$('#AllocationItems').bootstrapTable('copying', rowNew);
										}
										else {
											$("#AllocationItems").bootstrapTable('updateRow', {
												index: index, row: rowNew
											});
										}

									});
								}
							}
						},
						error: function () {
							$(this).showToastr('快速调拨异常！');
						}
					});
				});
			}

		});

		$("#IncomeWareHouseId").change(function () {
			if ($(this).val() == $("#ShipmentWareHouseId").val()) {
				$(this).showToastr("入货仓库与出货仓库不能相同！");
				return false;
			}
		});

		//商品列表选择赋值
		window.operateEventsPop = {
			'click .rowSelect': function (e, value, row, index) {

				try {

					var index = $(this).attr("data-id");

                    var keys = Object.keys(row.Units);
                    var allocationByMinUnit = $("#AllocationByMinUnit").val();
                    //默认价格
                    var price = row.Prices[0].ProductPrice.TradePrice;
                    //用户选择的价格体系
                    var defaultAmountId = 0;
                    //初始最小单位单位
                    var unitId = row.SmallUnitId;
                    var unitName = keys[0];
                    //如果不是最小单位
                    if (allocationByMinUnit != "1") {
                        //有大单位赋值大单位
                        if (row.BigUnitId != null && row.BigUnitId != 0) {
                            unitId = row.BigUnitId;
                            unitName = keys[2];
                            price = row.Prices[2].ProductPrice.TradePrice;
                        } else {
                            //有中单位赋值中单位
                            if (row.StrokeUnitId != null && row.StrokeUnitId != 0) {
                                unitId = row.StrokeUnitId;
                                unitName = keys[1];
                                price = row.Prices[1].ProductPrice.TradePrice;
                            }
                        }
                    }

                    //库存数量
                    var outgoingStock = 0;  //出库库存
                    var warehousingStock = 0; //入库库存

					var actualQty = 0;

                    var shipmentWareHouseId = $("#ShipmentWareHouseId").val(); //出库仓库
					var incomeWareHouseId = $("#IncomeWareHouseId").val(); //入库仓库

                    row.StockQuantities.forEach(function (a, b) {
                        if (a.WareHouseId == shipmentWareHouseId) {
                            outgoingStock = model.APPShowOrderStock == true ? a.CurrentQuantity : a.UsableQuantity;
                            actualQty = a.UsableQuantity;
                        }
                        if (a.WareHouseId == incomeWareHouseId) {
                            warehousingStock = a.UsableQuantity;
                        }
                    });

                    $("#AllocationItems").bootstrapTable('updateRow', {
                        index: index, row: {
                            ProductSKU: row.Sku,
                            ProductId: row.Id,
                            ProductName: row.Name,
                            BarCode: row.SmallBarCode,
                            UnitConversion: row.UnitConversion,
                            Units: row.Units,
                            UnitId: unitId,
                            UnitName: unitName,
                            Amount: 0,
                            Prices: row.Prices,
                            TradePrice: price,
                            WholesaleAmount: 0,
                            ProductTierPrices: row.ProductTierPrices,  //价格体系
                            OutgoingStock: outgoingStock,
                            StockQuantity: actualQty,
                            WarehousingStock: warehousingStock,
                            StockQuantities: row.StockQuantities, //库存数量
                            BigQuantity: row.BigQuantity,//大转小
                            StrokeQuantity: row.StrokeQuantity,//中转小
                            SmallUnitId: row.SmallUnitId,  //小单位
                            StrokeUnitId: row.StrokeUnitId,  //中单位
                            BigUnitId: row.BigUnitId  //大单位
                        }
                    });
                    $('#ModalProductWindows').modal('hide');
				}
				catch (err) {
					console.log(err);
					$(this).showToastr(err);
					return;
				}

			}
        };
		//项目
		$("#AllocationItems").bootstrapTable({
                @Html.Raw(Model.Items.Count > 0 ? "url: '/Allocation/AsyncAllocationItems?billId=" + Model.Id + "&data=" + Model.ModelLoadData + "'," : "length: 9,")
			striped: true,
			cache: false,
			pagination: true,
			showPagination: false,
			sidePagination: "server",
			sortable: false,
			sortOrder: "asc",
			search: false,
			strictSearch: false,
			showColumns: false,
			showRefresh: false,
			clickToSelect: false,
			uniqueId: "id",
			showToggle: false,
			editable: true,
			cardView: false,
			detailView: false,
			showFooter: true,
			onLoadSuccess: function (data) {
				$(".fixed-table-pagination").hide();
			},
            onPostBody: function (data) {
                $("[data-toggle='popover']").popover();
            },
			columns: [
				{
					title: '<i class="fa fa-gear fs18"></i>',
					width: '50',
					align: 'center',
					formatter: function (value, row, index) {
						return m_pagerow + index + 1;
					},
					footerFormatter: function (value) {
						return '总计';
					}
				},
				{ field: 'UnitId', visible: false },
				{ field: 'Units', visible: false },
				{ field: 'Prices', visible: false },
				{ field: 'ProductTierPrices', visible: false },  //价格体系
				{ field: 'SmallUnitId', visible: false }, //小单位
				{ field: 'StrokeUnitId', visible: false }, //中单位
				{ field: 'BigUnitId', visible: false }, //大单位
				{ field: 'ProductId', visible: false },
				{
					field: 'ProductSKU',
                    title: '商品编号',
                    formatter: $(this).formatIsNull
				},
				{
					field: 'ProductName',
					title: '商品名称',
                    width: '400',
					formatter: function (value) {
                        return (value == 0 || value == "" || value == undefined) ? "" : @Model.Id== 0 ? $(this).cutString(value, 70) : "<a style='color:black; text-decoration:none;'  data-trigger='hover' title='' data-container='body' data-toggle='popover' data-placement='top' data-content='" + value + "'>" + $(this).cutString(value, 70) + "</a>";
                    }
				},
				{
					field: 'BarCode',
                    title: '条形码',
                    formatter: $(this).formatIsNull
				},
				{
					field: 'UnitName',
                    title: '单位',
                    formatter: $(this).formatIsNull
				},
				{
					field: 'UnitConversion',
                    title: '单位换算',
                    formatter: $(this).formatIsNull
				},
				{
					field: 'Quantity',
                    title: '数量',
					formatter: $(this).formatIsNull,
                    footerFormatter: function (value) {
                        var count = 0;
                        var datas = $('#AllocationItems').bootstrapTable('getData');
                        var len = datas.length,
                            i, row;
                        //console.log(len);
                        if (len > 1) {
                            for (i = len - 1; i >= 0; i--) {
                                row = datas[i];
                                count += parseInt((typeof (row.Quantity) == 'undefined' || row.Quantity == "") ? '0' : row.Quantity);
                            }
                        }
                        else {
                            for (var i in value) {
                                count += parseInt((typeof (value[i].Quantity) == 'undefined' || value[i].Quantity == "") ? '0' : value[i].Quantity);
                            }
                        }
                        var total = parseInt((typeof (count) == 'undefined' || count == "") ? '0' : count);
                        return total;
                    }
                },
				{
					field: 'TradePrice',
					title: '批发价',
					formatter: $(this).formatFixed
				},
				{
					field: 'WholesaleAmount',
					title: '批发金额',
					formatter: $(this).formatFixed,
					footerFormatter: function (value) {
						var count = 0;
						var datas = $('#AllocationItems').bootstrapTable('getData');
						var len = datas.length,
							i, row;
						//console.log(len);
						if (len > 1) {
							for (i = len - 1; i >= 0; i--) {
								row = datas[i];
								count += parseFloat((typeof (row.WholesaleAmount) == 'undefined' || row.WholesaleAmount == "") ? '0' : row.WholesaleAmount);
							}
						}
						else {
							for (var i in value) {
								count += parseFloat((typeof (value[i].WholesaleAmount) == 'undefined' || value[i].WholesaleAmount == "") ? '0' : value[i].WholesaleAmount);
							}
						}
						var total = parseFloat((typeof (count) == 'undefined' || count == "") ? '0' : count).toFixed(2);
						return total;
					}
				},
				{
					field: 'OutgoingStock',
					title: '出库库存',
					align: 'center',
					width: '100',
					//formatter: $(this).formatUnitName
					formatter: function (value, row, index) {

						if (value != "" && row.ProductId != "" && row.ProductId > 0) {

							var bigUnitId = row.BigUnitId;
							var bigUnitName = "";
							var bigQuantity = row.BigQuantity;

							var strokeUnitId = row.StrokeUnitId;
							var strokeUnitName = "";
							var strokeQuantity = row.StrokeQuantity;

							var smallUnitId = row.SmallUnitId;
							var smallUnitName = "";

							$.each(row.Units, function (key, unit) {
								if (unit == bigUnitId) {
									bigUnitName = key;
								}
								else if (unit == strokeUnitId) {
									strokeUnitName = key;
								}
								else if (unit == smallUnitId) {
									smallUnitName = key;
								}
							});

							//计算结果数量
							var resultQuantity = value;
							//大单位计算结果
							var big = parseInt(resultQuantity / row.BigQuantity);
							resultQuantity = resultQuantity - big * row.BigQuantity;
							//中单位计算结果
							var stroke = 0;
							if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
								stroke = parseInt(resultQuantity / row.StrokeQuantity);
								resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
							}
							//小单位计算结果
							var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

							 if (small > 0)
                                content += small + "" + smallUnitName

							return "<span alt=" + value + ">" + content + "</span>";

						}
						else {
							return "";
						}
					}
                },
                {
                    //field: 'StockQuantity',
                    field: 'StockQuantity',
                    title: '出库可用库存',
                    align: 'center',
                    width: '100',
                    formatter: function (value, row, index) {

						if (value != "" && value != undefined && row.ProductId != "" && row.ProductId > 0) {

                            var bigUnitId = row.BigUnitId;
                            var bigUnitName = "";
                            var bigQuantity = row.BigQuantity;

                            var strokeUnitId = row.StrokeUnitId;
                            var strokeUnitName = "";
                            var strokeQuantity = row.StrokeQuantity;

                            var smallUnitId = row.SmallUnitId;
                            var smallUnitName = "";

                            $.each(row.Units, function (key, unit) {
                                if (unit == bigUnitId) {
                                    bigUnitName = key;
                                }
                                else if (unit == strokeUnitId) {
                                    strokeUnitName = key;
                                }
                                else if (unit == smallUnitId) {
                                    smallUnitName = key;
                                }
                            });

                            //计算结果数量
                            var resultQuantity = value;
                            //大单位计算结果
                            var big = parseInt(resultQuantity / row.BigQuantity);
                            resultQuantity = resultQuantity - big * row.BigQuantity;
                            //中单位计算结果
                            var stroke = 0;
                            if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
                                stroke = parseInt(resultQuantity / row.StrokeQuantity);
                                resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
                            }
                            //小单位计算结果
							var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

							 if (small > 0)
                                content += small + "" + smallUnitName

							return "<span alt=" + value + ">" + content + "</span>";
                        }
                        else {
                            return "";
                        }
                    },
                    visible: model.APPShowOrderStock
                },
				{
					field: 'WarehousingStock',
					title: '入库库存',
					align: 'center',
					width: '100',
					//formatter: $(this).formatUnitName
					formatter: function (value, row, index) {

						if (value != "" && row.ProductId != "" && row.ProductId > 0) {

							var bigUnitId = row.BigUnitId;
							var bigUnitName = "";
							var bigQuantity = row.BigQuantity;

							var strokeUnitId = row.StrokeUnitId;
							var strokeUnitName = "";
							var strokeQuantity = row.StrokeQuantity;

							var smallUnitId = row.SmallUnitId;
							var smallUnitName = "";

							$.each(row.Units, function (key, unit) {
								if (unit == bigUnitId) {
									bigUnitName = key;
								}
								else if (unit == strokeUnitId) {
									strokeUnitName = key;
								}
								else if (unit == smallUnitId) {
									smallUnitName = key;
								}
							});

							//计算结果数量
							var resultQuantity = value;
							//大单位计算结果
							var big = parseInt(resultQuantity / row.BigQuantity);
							resultQuantity = resultQuantity - big * row.BigQuantity;
							//中单位计算结果
							var stroke = 0;
							if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
								stroke = parseInt(resultQuantity / row.StrokeQuantity);
								resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
							}
							//小单位计算结果
							var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

							 if (small > 0)
                                content += small + "" + smallUnitName

							return "<span alt=" + value + ">" + content + "</span>";
						}
						else {
							return "";
						}
					}
				},
				{
					field: 'Remark',
                    title: '备注',
                    formatter: $(this).formatIsNull
				},
				{
					field: 'Operate',
					title: '操作',
					align: 'center',
					width: '120',
					events: {
						'click .rowAppend': function (e, value, row, index) {// 添加
							//审核、红冲后不能修改
							if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
								return false;
							}
							$('#AllocationItems').bootstrapTable('insert', row);

                            //修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
                            var allTableData = $('#AllocationItems').bootstrapTable('getData');
                            var maxuniqueid = 0;
                            $.each(allTableData, function (i, row) {
                                if (row.uniqueid > maxuniqueid) {
                                    maxuniqueid = row.uniqueid;
                                }
                            });
							allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
                            allTableData[allTableData.length - 1].Id = 0;
						},
						'click .rowCopy': function (e, value, row, index) {// 复制
							//审核、红冲后不能修改
							if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
								return false;
							}
							$('#AllocationItems').bootstrapTable('copying', row);
							//修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
							var allTableData = $('#AllocationItems').bootstrapTable('getData');
							var maxuniqueid = 0;
							$.each(allTableData, function (i, row) {
								if (row.uniqueid > maxuniqueid) {
									maxuniqueid = row.uniqueid;
								}
							});
							allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
							allTableData[allTableData.length - 1].Id = 0;
                            allTableData[allTableData.length - 1].IsGifts = false;
						},
						'click .rowDel': function (e, value, row, index) {// 删除
							//审核、红冲后不能修改
							if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
								return false;
							}
							var datas = $('#AllocationItems').bootstrapTable('getData');
							var len = datas.length;
							if (len == 1) {
								//$(this).showToastr('数据不能删除');
                                $(this).showToastr('单据项目不能留空');
								return;
							}

							if (typeof (row.uniqueid) == "undefined") {
                                $("#AllocationItems").bootstrapTable('remove', { field: "Id", values: [parseInt(row.Id)] });
							}
							else {
								$("#AllocationItems").bootstrapTable('remove', { field: "uniqueid", values: [parseInt(row.uniqueid)] });
							}
						}
					},
					formatter: function (value, row, index) {
						return [
							'<button type="button" class="btn btn-sm btn-default rowAppend" title="添加"><i class="fa fa-plus" ></i></button>',
							'<button type="button" class="btn btn-sm btn-default rowCopy" title="复制"><i class="fa fa-copy" ></i></button>',
							'<button type="button" class="btn btn-sm btn-default rowDel" title="删除"><i class="fa fa-trash-o"></i></button>'
						].join('');
					}
				}
			],
			onClickCell: function (field, value, row, $element) {

				if (field == "Operate") {
					return false;
				}

				var input = $($element).find("input");
				var select = $($element).find("select");
				if (input.length > 0 || select.length > 0)
					return false;
				//当前列所在行的索引
				var index = $element.parent().attr("data-index");

				//审核、红冲后不能修改
				if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
					return false;
				}

				if (field == "ProductName") {
					var html = '<div class="input-group">' +
						'<input type="text" class="form-control input-sm"  name="ProductName" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">' +
						'<span class="input-group-btn"><button type="button" class="btn btn-default btn-sm searchproduct" id="search_' + field + "_" + row.Id + '" data-index="' + index + '"><span class="glyphicon glyphicon-search"></span></button></span>' +
						'</div>';
					$($element).html(html);
					var inputObj = $("#search_" + field + "_" + row.Id);
					inputObj.focus();
					inputObj.select();
					inputObj.bind("focusout", function () {
						$("#AllocationItems").bootstrapTable('updateRow', { index: index, row: { ProductName: value } });
						$($element).html("" + value + "");
					});
					//选择商品
					inputObj.bind("click", function () {
						//$(this).productSelectShowModal($("#ModalProductWindows"), "/Product/AsyncSearchSelectPopup", { Index: $(this).attr("data-index") }, "选择商品", $("#ProductModalForm"),
						//	function () { });
						var wareHouseId = $("#ShipmentWareHouseId").val();
						$(this).productSelectShowModal($("#ModalProductWindows"), "/Product/AsyncSearchSelectPopup?wareHouseId=" + wareHouseId + "&stockQtyMoreThan=true&includeProductDetail=0", { Index: $(this).attr("data-index") }, "选择商品", $("#ProductModalForm"),
							function () { });

					});
				}
				else if (["Quantity"].indexOf(field) >= 0) {
					var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "0" : value) + '" id="' + field + "_" + row.Id + '">';
					$($element).html(html);
					var inputObj = $("#" + $(html).attr("id"));
					inputObj.focus();
					inputObj.select();
					inputObj.bind("focusout", function () {
                        if (!isNaN($(this).val())) {
                            row[field] = $(this).val();
                            var tradePrice = (row.TradePrice == null || row.TradePrice == "") ? 0 : row.TradePrice;
                            var wholesaleAmount = parseFloat(tradePrice) * parseFloat($(this).val());
                            wholesaleAmount = isNaN(wholesaleAmount) ? 0 : wholesaleAmount;
                            $("#AllocationItems").bootstrapTable('updateRow', { index: index, row: { WholesaleAmount: parseFloat(wholesaleAmount) } });
                            $($element).html("" + value + "");
                        }
						else {
							$(this).val(0);
                            $(this).showToastr("只能输入数字!");
                            return false;
                        }
					});
				}
				else if (field == "Remark") {
					var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">';
					$($element).html(html);
					var inputObj = $("#" + $(html).attr("id"));
					inputObj.focus();
					inputObj.select();
					inputObj.bind("focusout", function () {
						$("#AllocationItems").bootstrapTable('updateRow', { index: index, row: { Remark: $(this).val() } });
						$($element).html("" + value + "");
					});
				}
				else if (field == "UnitName") {

					console.log("Units:" + row.Units);

					if (row.Units == null) {
						$(this).showToastr('请选择商品');
						return;
					}

					console.log("UnitId:" + row.UnitId);

					var html = '<select name="' + field + '" id="' + field + "_" + row.Id + '">';
					//var keys = Object.keys(row.Units);
					$.each(row.Units, function (key, unit) {
						if (unit > 0) {
							html += '<option value="' + unit + '"  ' + (row.UnitId == unit ? "selected" : "") + '>' + key + '</option>';
						}
					});
					html += '</select>';

					$($element).html(html);

					var inputObj = $("#" + $(html).attr("id"));
					inputObj.focus();
					inputObj.select();
					inputObj.bind("focusout", function () {
						$($element).html("" + inputObj.find("option:selected").text() + "");
					});

					//单位选择
					inputObj.bind("change", function () {
						//console.log($(this).val());
						//console.log($(this).find("option:selected").text());
						//console.log(row.Prices);
						var curUnit = parseInt($(this).val());
						var tradePrice = 0;
						$.each(row.Prices, function (i, price) {
							if (curUnit == price.UnitId) {
								tradePrice = price.ProductPrice != null ? price.ProductPrice.TradePrice : 0;
							}
						});
						var wholesaleAmount = parseFloat(parseFloat((row.Quantity == undefined || row.Quantity=="") ? "0" : row.Quantity) * parseFloat(tradePrice)).toFixed(2);
						$("#AllocationItems").bootstrapTable('updateRow', {
							index: index,
							row: {
								UnitId: curUnit,
								UnitName: $(this).find("option:selected").text(),
								TradePrice: tradePrice,
								WholesaleAmount: wholesaleAmount
							}
						});
					});
				}
				//debug
				$.each($('#AllocationItems').bootstrapTable('getData'), function (i, row) {
					//console.log(row);
				});
			}
		});

        //表单检查
		var formValidator = function () {
            var isVaild = true;

            var allTableData = $('#AllocationItems').bootstrapTable('getData');
            var flag = 0;
            $.each(allTableData, function (i, row) {
                if (row.ProductId == "" || row.Quantity == "")
                    flag++;
            });

            if ($("#ShipmentWareHouseId").val() == "" || $("#ShipmentWareHouseId").val() == "0") {
                $("#ShipmentWareHouseId").focus();
                $(this).showToastr("请选择出货仓库！");
                return false;
            }
            else if ($("#IncomeWareHouseId").val() == "" || $("#IncomeWareHouseId").val() == "0") {
                $("#IncomeWareHouseId").focus();
                $(this).showToastr("请选择入货仓库！");
                return false;
            }
            else if ($("#ShipmentWareHouseId").val() == $("#IncomeWareHouseId").val()) {
                $(this).showToastr("入货仓库与出货仓库不能相同！");
                return false;
            }
            else if (flag == allTableData.length) {
                $(this).showToastr("请先添加单据项目!");
                return false;
            }

			return isVaild;
		}

		//保存服务器
        var submitRemoteServer = function (showMessage, doAudit, callback,loadingButton) {

            if (!formValidator()) {
	            if(loadingButton != undefined){
				   loadingButton.stop();
			    }
				return false;
			};


			//获取表格的所有内容行
            var allTableData = $('#AllocationItems').bootstrapTable('getData');
			var serializeData = [];
            $.each(allTableData, function (i, row) {
				var tmpObj = {
					Id: (!row.Id || typeof (row.Id) == 'undefined' || row.Id == "") ? "0" : row.Id,
					ProductId: (!row.ProductId || typeof (row.ProductId) == 'undefined' || row.ProductId == "") ? "0" : row.ProductId,
					UnitId: (!row.UnitId || typeof (row.UnitId) == 'undefined' || row.UnitId == "") ? "0" : row.UnitId,
					Quantity: (!row.Quantity || typeof (row.Quantity) == 'undefined' || row.Quantity == "") ? "0" : row.Quantity,
					TradePrice: (!row.TradePrice || typeof (row.TradePrice) == 'undefined' || row.TradePrice == "") ? "0" : row.TradePrice,
					WholesaleAmount: (!row.WholesaleAmount || typeof (row.WholesaleAmount) == 'undefined' || row.WholesaleAmount == "") ? "0" : row.WholesaleAmount,
					OutgoingStock: (!row.OutgoingStock || typeof (row.OutgoingStock) == 'undefined' || row.OutgoingStock == "") ? "0" : row.OutgoingStock,
					WarehousingStock: (!row.WarehousingStock || typeof (row.WarehousingStock) == 'undefined' || row.WarehousingStock == "") ? "0" : row.WarehousingStock,
                    Remark: (!row.Remark || typeof (row.Remark) == 'undefined' || row.Remark == "") ? "" : row.Remark
				};
				if (tmpObj.ProductId != 0)
					serializeData.push(tmpObj);
			});

			//保存的数据
			var postData = {
				ShipmentWareHouseId: $("#ShipmentWareHouseId").val(),
				IncomeWareHouseId: $("#IncomeWareHouseId").val(),
				AllocationByMinUnit: $("#AllocationByMinUnit").val(),
				Remark: $("#Remark").val(),
				Items: serializeData,
                //单号
                BillNumber: $("#BillNumber").val(),
			};

			//debug
			//console.log(postData);
			//return false;

            //保存服务器
            $(this).remoteSubmit("post", "/Allocation/CreateOrUpdate?billId=@(Model.Id)&doAudit=" + doAudit, postData, $("#AllocationItems"), callback, showMessage,loadingButton);

		};

		//保存单据项目
		$("#FormSubmit").click(function () {
			var doAudit = true;
	        //防止重复保存
		    var loadingButton = Ladda.create(this);
			loadingButton.start();
            submitRemoteServer(null, doAudit,function (data) {
                if (data.Success) {
                    window.location.href = "/Allocation/List";
                }
            }, loadingButton);
		});

		//保存并继续
		$("#FormSubmitContinue").click(function () {
			var doAudit = false;
	        //防止重复保存
			var loadingButton = Ladda.create(this);
			loadingButton.start();
            submitRemoteServer(null,doAudit,null,loadingButton);
		});


		//审核
        $(document).on('click', "#btn_auditing", function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);
			loadingButton.start();
			var returnUrl = "@Context.Request.Query["returnURL"]";
            if (returnUrl.indexOf("AuditedStatus=") == -1) {
                if (returnUrl.indexOf("?") == -1) {
                    returnUrl += "?";
                } else {
                    returnUrl += "&";
                }
                returnUrl += "AuditedStatus=False";
            } else {
                if (returnUrl.indexOf("AuditedStatus=False") == -1) {
                    returnUrl = returnUrl.replace("AuditedStatus=", "AuditedStatus=False");
                }
            }
            returnUrl = returnUrl.replace(/amp;/g, "");
            $(this).remoteSubmit("get", "/Allocation/Auditing", { id: "@Model.Id" }, null, function () { location.href = returnUrl; }, null, loadingButton);

	        @*//防止重复保存
	        var loadingButton = Ladda.create(this);
	        loadingButton.start();
			submitRemoteServer(false, function () {
				//var allTableData = $('#PurchaseItems').bootstrapTable('getData');
				//var flag = 0;
				//$.each(allTableData, function (i, row) {
				//	if (row.ProductId == "" || row.Quantity == "")
				//		flag++;
				//});

				//if (flag == allTableData.length) {
				//	$(this).showToastr("请先填写单据明细！");
				//	return false;
				//}

				$(this).remoteSubmit("get", "/Allocation/Auditing", { id: "@Model.Id" }, null, function () { location.href = "/Allocation/List"; }, null,loadingButton);
			},loadingButton);*@
		});

		//红冲
		$(document).on('click', "#btn_reversed", function () {
	        //防止重复保存
		    var loadingButton = Ladda.create(this);

            WinMsg.confirm({ message: "确认要红冲吗？" }).on(function (e) {
				if (!e) {
					return;
				}
	            loadingButton.start();
				$(this).remoteSubmit("get", "/Allocation/Reverse", { id: "@Model.Id" }, null, function () { location.href = "/Allocation/List"; }, null,loadingButton);
			});
		});

		//打印
		$("#btn_print").click(function () {
	        //防止重复保存
	        var loadingButton = Ladda.create(this);
            WinMsg.confirm({ message: "确认要打印吗？" }).on(function (e) {
				if (!e) {
					return;
				}
				loadingButton.start();
                var setting = {}
                var LODOP = null;
                var rs = $(this).getSyncData("/Allocation/PrintSetting", null, "get");
				if (rs.Success) {
					setting = rs.Data;
					loadCLodop(document, setting.PrintPort, () => {
						//判断页面是否已加载LODOP
						if (LODOP == null || LODOP == undefined) {
							LODOP = getLodopFirst(document);
							LODOP = getLodopSecond(document);
						}
						if (LODOP == null || LODOP == undefined) {
							loadingButton.stop();
							return;
						} else {
							$("#printData").html("");
						}
						$(this).remoteSubmit("get", "/Allocation/Print", { selectData: "@Model.Id" }, null, function (result) {
							if (result.Success) {
								var html = result.Data;
								LODOP.PRINT_INIT("调拨单");
								if (!isNaN(setting.PaperWidth) && !isNaN(setting.PaperHeight)) {
									LODOP.SET_PRINT_PAGESIZE(1, setting.PaperWidth + "mm", setting.PaperHeight + "mm");
								}
								if (setting.IsPrintPageNumber) {
									LODOP.ADD_PRINT_HTM(1, 600, 300, 100, "总页号：<font color='#0000ff' format='ChineseNum'><span tdata='pageNO'>第##页</span>/<span tdata='pageCount'>共##页</span></font>");
								}
								if (!isNaN(setting.MarginTop) && !isNaN(setting.MarginLeft) && !isNaN(setting.MarginRight) && !isNaN(setting.MarginBottom)) {
									LODOP.ADD_PRINT_HTM(setting.MarginTop + "mm", setting.MarginLeft + "mm", "RightMargin:" + setting.MarginRight + "mm", "BottomMargin:" + setting.MarginBottom + "mm", html);
								}
                                LODOP.SET_PRINT_STYLEA(0, "Horient", 2);
								LODOP.PREVIEW(true);
								loadingButton.stop();
							}
							else {
								$(this).showToastr(result.Message);
							}
						}, null, loadingButton);
					});
				}

			});
        });


		//作废
        $(document).on('click', "#btn_cancel", function () {
	        //防止重复保存
		    var loadingButton = Ladda.create(this);

            WinMsg.confirm({ message: "确认要作废吗？" }).on(function (e) {
				if (!e) {
					return;
				}
	            loadingButton.start();
                $(this).remoteSubmit("get", "/Allocation/Delete", { id: "@Model.Id" }, null, function () { location.href = "/Allocation/List"; }, null,loadingButton);
			});
		});
	});
</script>